package com.gzyj.server.nettyserver.handler;

import com.gzyj.server.config.LogConfig;
import com.gzyj.server.factory.jtt808.Common808HandlerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gzyj.jtt808.v2013.Package;

/**
 * @author lhj
 */

@Component
@ChannelHandler.Sharable
public class DispatcherHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    Common808HandlerFactory handlerFactory;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof Package){
            Package pack = (Package) msg;
            if (handlerFactory.getHandler(pack.getPackageHeader().getMsgId()) == null) {
                LogConfig.commondLog.warn("808 2013版 暂不支持此类型消息：" + pack.getPackageHeader().getMsgId());
                return;
            }
            handlerFactory.getHandler(pack.getPackageHeader().getMsgId()).handler(ctx, pack);
        }else if(msg instanceof com.gzyj.jtt808.v2019.Package){
            com.gzyj.jtt808.v2019.Package pack=(com.gzyj.jtt808.v2019.Package)msg;
            if (handlerFactory.getHandler(pack.getPackageHeader().getMsgId()) == null) {
                LogConfig.commondLog.warn("808 2019版 暂不支持此类型消息：" + pack.getPackageHeader().getMsgId());
                return;
            }
            handlerFactory.getHandler(pack.getPackageHeader().getMsgId()).handler(ctx, pack);
        }else if(msg instanceof com.gzyj.jtt808.v2011.Package){
            com.gzyj.jtt808.v2011.Package pack=(com.gzyj.jtt808.v2011.Package)msg;
            if (handlerFactory.getHandler(pack.getPackageHeader().getMsgId()) == null) {
                LogConfig.commondLog.warn("808 2011版 暂不支持此类型消息：" + pack.getPackageHeader().getMsgId());
                return;
            }
            handlerFactory.getHandler(pack.getPackageHeader().getMsgId()).handler(ctx, pack);
        }else if(msg instanceof ByteBuf){
            ctx.fireChannelRead(msg);
        }
    }

}
